package com.zztl.infiniteBand.net

import com.zztl.infiniteBand.storage.BillPreference
import com.zztl.infiniteBand.storage.PreferenceKeys
import com.zztl.infiniteBand.util.LogUtils
import com.zztl.infiniteBand.util.UiUtils
import com.zztl.infiniteBand.util.language.SPUtil
import okhttp3.Headers
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import okio.Buffer
import java.io.IOException
import java.lang.StringBuilder
import java.util.*

/**
 * @desc  添加公共参数的拦截器
 * @auth ${user}
 * @time 2018/3/14  16:35
 */

class HttpCommonInterceptor : Interceptor {
    private val headerParams = HashMap<String, String>()
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val oldRequest = chain.request()


        /*      long t1 = System.nanoTime();//请求发起的时间
        LogUtils.i("HTTP",String.format("发送请求 %s on %s",
                oldRequest.url(), oldRequest.body().getClass().getName()));
*/

        val tokenizer = BillPreference.getApp(PreferenceKeys.TOKEN.name, "") as String?

        val builder = oldRequest.newBuilder()
                .addHeader("authorization", tokenizer)
                .addHeader("Accept-Language",if(SPUtil.getInstance(UiUtils.context)?.selectLanguage==0) "en-US" else "zh-CN")
        builder.method(oldRequest.method(), oldRequest.body())


        if (headerParams.size > 0) {
            for ((key, value) in headerParams) {
                builder.addHeader(key, value)
            }
        }



        val newRequest = builder.build()

        LogUtils.e("Http", "发送请求:${newRequest.method()}请求头${hearderToStr(newRequest.headers())} oldRequest.url() requestBody  ${bodyToString(newRequest)}")

        val response = chain.proceed(newRequest)
        val responseBody = response.peekBody((1024 * 1024).toLong())
        LogUtils.e("Http", "接收响应: " + response.request().url() + " 状态码： " + response.code() + "\njson: " + responseBody.string())
        return response
    }

    class Builder {
        var mHttpCommonInterceptor: HttpCommonInterceptor

        init {
            mHttpCommonInterceptor = HttpCommonInterceptor()
        }

        fun addHeaderParams(key: String, value: String): Builder {
            mHttpCommonInterceptor.headerParams[key] = value
            return this
        }

        fun addHeaderParams(key: String, value: Int): Builder {
            return addHeaderParams(key, value.toString())
        }

        fun addHeaderParams(key: String, value: Float): Builder {
            return addHeaderParams(key, value.toString())
        }

        fun addHeaderParams(key: String, value: Long): Builder {
            return addHeaderParams(key, value.toString())
        }

        fun addHeaderParams(key: String, value: Double): Builder {
            return addHeaderParams(key, value.toString())
        }

        fun build(): HttpCommonInterceptor {
            return mHttpCommonInterceptor
        }
    }



    private fun hearderToStr(headers: Headers):String{
        val builder:StringBuilder= StringBuilder()
       for (i in 0 until headers.size()) {
           headers.name(i)?.run {
               builder.append(this).append("=").append(headers.get(this)).append(",")
           }

       }
        return builder.toString()

    }

    private fun bodyToString(request: Request): String {
        try {
            if (request.body() != null) {
                val copy = request.newBuilder().build()
                val buffer = Buffer()
                copy.body().writeTo(buffer)
                return buffer.readUtf8()
            } else {
                return "null"
            }

        } catch (e: IOException) {
            return "did not work"
        }

    }
}
